//
//  CategorySortViewModel.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 02.04.25.
//

import SwiftUI

class CategorySortViewModel : KoiAccountingBaseViewModel {
    
    @Published var categoryList = Array<AccountingCategory>()
    
    private let categoryDao = KoiAccountingDB.standard.getCategoryDao()
    
    func loadCategorys(type: String) {
        asyncBackground {
            let result = self.categoryDao.getCategoryByType(uid: self.uid, bookId: self.bookId, type: type)
            self.asyncMain {
                self.categoryList = result
            }
        }
    }
    
    func loadSubCategorys(parentId: String) {
        asyncBackground {
            let result = self.categoryDao.getSubCategoryListByParentId(uid: self.uid, bookId: self.bookId, parentId: parentId)
            self.asyncMain {
                self.categoryList = result
            }
        }
    }
    
    func updateCategoryOrder() {
        for (index, _) in categoryList.enumerated() {
            categoryList[index].orderId = index + 1
        }
        asyncBackground {
            self.categoryDao.update(categorys: self.categoryList)
        }
    }
}
